<template>
	<a-card :bordered="false" :body-style="{ 'padding-bottom': '0px' }" class="mb-2">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="物品名称" name="goodsName">
						<a-input v-model:value.trim="searchFormState.goodsName" placeholder="请输入物品名称"></a-input>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="台账类型" name="ledgerType">
						<a-select v-model:value="searchFormState.ledgerType" placeholder="请选择" allowClear>
							<a-select-option value="0">首次入库</a-select-option>
							<a-select-option value="1">启用</a-select-option>
							<a-select-option value="2">维修</a-select-option>
							<a-select-option value="3">报废</a-select-option>
							<a-select-option value="10">取用</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="操作时间" name="optStartDate">
						<a-date-picker v-model:value="searchFormState.optStartDate" :disabled-date="disabledStartDate"
									   :format="dateFormat"/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-form-item label="" name="optEndDate">
						<a-date-picker v-model:value="searchFormState.optEndDate" :disabled-date="disabledEndDate"
									   :format="dateFormat"/>
					</a-form-item>
				</a-col>

				<a-col :span="6">
					<a-form-item label="领用检查有不合格项" name="borCheckUnqFlag">
						<a-switch v-model:checked="searchFormState.borCheckUnqFlag" checked-children="有"
								  un-checked-children="无"/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="领用检查有未检查项" name="borCheckNotFlag">
						<a-switch v-model:checked="searchFormState.borCheckNotFlag" checked-children="有"
								  un-checked-children="无"/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="归还检查有不合格项" name="retCheckUnqFlag">
						<a-switch v-model:checked="searchFormState.retCheckUnqFlag" checked-children="有"
								  un-checked-children="无"/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="归还检查有未检查项" name="retCheckNotFlag">
						<a-switch v-model:checked="searchFormState.retCheckNotFlag" checked-children="有"
								  un-checked-children="无"/>
					</a-form-item>
				</a-col>

				<a-col :span="6">
					<a-form-item label="物品ID" name="goodsId">
						<a-input v-model:value.trim="searchFormState.goodsId" placeholder="请输入物品ID"></a-input>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-button type="primary" @click="table.refresh(true)">查询</a-button>
					<a-button style="margin: 0 8px" @click="() => resetForm()">重置</a-button>
					<a-button type="primary" ghost @click="exportGoodsLedger()" :loading="exportLoading">导出</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false">
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 2450 }"
		>
			<template #operator class="table-operator">
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'goodsName'">
					<span v-if="record.goodsName">{{record.goodsName}}</span>
					<span v-else>
						<a-tag color="red">未知</a-tag>
					</span>
				</template>
				<template v-if="column.dataIndex === 'abnNum'">
					<a-tag v-if="record.abnNum> 0" color="red" @click="jumpEventForLedger(record)">
						{{record.abnNum}}
					</a-tag>
					<a-tag color="green" v-else>
						无
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'collectionInspectionRecord'">
					<a-space v-if="record.ledgerType===10" :size="1">
						<a-tag color="green" @click="checkItemsRef.onOpen(record.id,0)">合格:
							{{record.borCheckQualifyNum}}
						</a-tag>
						<a-tag color="red" @click="checkItemsRef.onOpen(record.id,0)">不合格: {{record.borCheckUnqNum}}
						</a-tag>
						<a-tag color="blue" @click="checkItemsRef.onOpen(record.id,0)">未检查: {{record.borCheckNotNum}}
						</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'returnInspectionRecord'">
					<a-space v-if="record.ledgerType===10" :size="1">
						<a-tag color="green" @click="checkItemsRef.onOpen(record.id,1)">合格:
							{{record.retCheckQualifyNum}}
						</a-tag>
						<a-tag color="red" @click="checkItemsRef.onOpen(record.id,1)">不合格: {{record.retCheckUnqNum}}
						</a-tag>
						<a-tag color="blue" @click="checkItemsRef.onOpen(record.id,1)">未检查: {{record.retCheckNotNum}}
						</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'ledgerType'">
					<a-space>
						<a-tag v-if="record.ledgerType === 0" color="blue">首次入库</a-tag>
						<a-tag v-if="record.ledgerType === 1" color="green">启用</a-tag>
						<a-tag v-if="record.ledgerType === 2" color="purple">维修</a-tag>
						<a-tag v-if="record.ledgerType === 3" color="red">报废</a-tag>
						<a-tag v-if="record.ledgerType === 10" color="orange">取用</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'createUserName'">
					<span v-if="record.createUserName">{{record.createUserName}}({{record.createUserAccount}})</span>
				</template>
				<template v-if="column.dataIndex === 'deliveryUserName'">
					<span v-if="record.deliveryUserName">{{record.deliveryUserName}}({{record.deliveryUserAccount}})</span>
				</template>
				<template v-if="column.dataIndex === 'warehouseUserName'">
					<span v-if="record.warehouseUserName">{{record.warehouseUserName}}({{record.warehouseUserAccount}})</span>
				</template>
			</template>
		</s-table>
	</a-card>
	<CheckItems ref="checkItemsRef"/>
</template>

<script setup name="goodsledger">
	import bizGoodsLedgerApi from '@/api/biz/bizGoodsLedgerApi'
	import dayjs from 'dayjs';
	import { useRoute, useRouter } from 'vue-router'
	import CheckItems from "./checkItems.vue"

	const dateFormat = 'YYYY-MM-DD';
	const router = useRouter()
	let searchFormState = reactive({})
	const searchFormRef = ref()
	const checkItemsRef = ref()
	const table = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	//导出loading
	const exportLoading = ref(false)

	const columns = [
		{
			title: '物品名称',
			dataIndex: 'goodsName',
			fixed: true,
			width: 150
		},
		{
			title: '台账类型',
			dataIndex: 'ledgerType',
			width: 150
		},
		{
			title: '操作时间',
			dataIndex: 'createTime',
			width: 150
		},
		{
			title: '操作人',
			dataIndex: 'createUserName',
			width: 150
		},
		{
			title: '出库时间',
			dataIndex: 'deliveryTime',
			width: 150
		},
		{
			title: '出库用户',
			dataIndex: 'deliveryUserName',
			width: 150
		},
		{
			title: '入库时间',
			dataIndex: 'warehouseTime',
			width: 150
		},
		{
			title: '入库用户',
			dataIndex: 'warehouseUserName',
			width: 150
		},
		{
			title: '异常事件',
			dataIndex: 'abnNum',
			width: 150
		},
		{
			title: '领用检查时间',
			dataIndex: 'collectionInspectionTime',
			width: 150
		},
		{
			title: '领用检查记录',
			dataIndex: 'collectionInspectionRecord',
			width: 250
		},
		{
			title: '借后检查时间间隔（分钟）',
			dataIndex: 'collectionInspectionInterval',
			width: 150
		},
		{
			title: '归还检查时间',
			dataIndex: 'returnInspectionTime',
			width: 150
		},
		{
			title: '归还检查记录',
			dataIndex: 'returnInspectionRecord',
			width: 250
		},
		{
			title: '还前检查时间间隔（分钟）',
			dataIndex: 'returnInspectionInterval',
			width: 150
		}
	]

	let selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		return bizGoodsLedgerApi.bizGoodsLedgerPage(Object.assign(parameter, searchFormState)).then((data) => {
			return data
		})
	}
	const disabledStartDate = (current) => {
		return current && current >= dayjs(searchFormState.optEndDate);
	};

	const disabledEndDate = (current) => {
		return current && current <= dayjs(searchFormState.optStartDate);
	};

	const exportGoodsLedger = () => {
		exportLoading.value = true
		bizGoodsLedgerApi.bizGoodsLedgerExport( searchFormState ).then((res) => {
			const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' });
			const contentDisposition = res.headers['content-disposition']
			const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
			const $link = document.createElement("a");
			$link.href = URL.createObjectURL(blob);
			var reg = /^["](.*)["]$/g
			$link.download = decodeURI(patt.exec(contentDisposition)[1].replace(reg, '$1'))
			$link.click();
			document.body.appendChild($link);
			document.body.removeChild($link); // 下载完成移除元素
			window.URL.revokeObjectURL($link.href); // 释放掉blob对象
		}).finally(() => {
			exportLoading.value = false
		})
	}

	watch(
		() => router.currentRoute.value,
		(newValue, oldValue) => {
			if (newValue.name === 'bizGoodsledger') {
				let params = newValue.params
				console.log('params=', params)
				if(params) {
					//接收路由参数
					let goodsId = params.goodsId
					if (goodsId && goodsId !== searchFormState.goodsId) {
						console.log('goodsId=', goodsId)
						searchFormState.goodsId = goodsId
						// 加载数据
						if (table.value) {
							table.value.refresh(true)
						}
					}
				}

			}
		},
		{
			immediate: true
		}
	)

	//跳转到事件
	const jumpEventForLedger = (data) => {
		router.replace({
			name: 'bizEvent',
			params: {
				goodsLedgerId: data.id,
				abnFlag: 1
			}
		})
	}

	const resetForm = () => {
		searchFormRef.value.resetFields()
		searchFormState.goodsId = null
		table.value.refresh(true)
	}
</script>
